﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Routing;
using System.Web.Security;
using System.Web.SessionState;
using Ivy.Common.Framework.GeneralUtility;
using System.Configuration;
using FrameworkIvy.App_Code;
using Ivy.SiteAdministration.Entity;
using Ivy.SiteAdministration.IBusinessLogic;
using Ivy.SiteAdministration.BusinessLogic;

namespace FrameworkIvy
{
    public class Global : System.Web.HttpApplication
    {
        const string _TheDefaultUserContextSessionVariableName = "UserContext";

        void Application_Start(object sender, EventArgs e)
        {
            // Code that runs on application startup

        }

        void Application_End(object sender, EventArgs e)
        {
            //  Code that runs on application shutdown

        }

        void Application_Error(object sender, EventArgs e)
        {
            // Code that runs when an unhandled error occurs

        }

        void Session_Start(object sender, EventArgs e)
        {
            // Code that runs when a new session is started
            UserContext tempUserSession = new UserContext();
            tempUserSession.UserSessionID = tempUserSession.GetCurrentSessionID();
            tempUserSession.CultureInfo = tempUserSession.GetDefaultCultureInfo();
            tempUserSession.UserIPAddress = tempUserSession.GetCurrentSessionIPAddress();
            tempUserSession.UserBrowser = tempUserSession.GetCurrentSessionBrowserName();
            tempUserSession.UserSessionStartTime = DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString();
            tempUserSession.ResetCurrentUser();
            tempUserSession.ResetCurrentUserOrganizationRoles();
            Session[_TheDefaultUserContextSessionVariableName] = tempUserSession;
            WriteSessionLog(tempUserSession);

        }

        void Session_End(object sender, EventArgs e)
        {
            // Code that runs when a session ends. 
            // Note: The Session_End event is raised only when the sessionstate mode
            // is set to InProc in the Web.config file. If session mode is set to StateServer 
            // or SQLServer, the event is not raised.

        }

        #region Private Methods
        //private string GetUserIPAddress()
        //{
        //    //The X-Forwarded-For (XFF) HTTP header field is a de facto standard for identifying the originating IP address of a 
        //    //client connecting to a web server through an HTTP proxy or load balancer
        //    string ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
        //    if (string.IsNullOrEmpty(ip))
        //    {
        //        ip = HttpContext.Current.Request.UserHostAddress;
        //        if (string.IsNullOrEmpty(ip))
        //        {
        //            ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
        //        }
        //    }
        //    return ip;
        //}

        //private string GetUserCultureInfo()
        //{
        //    //Currently we are treating all user with same cultural info. We will change ir based of user session.
        //    AppSettingsReader _AppSettingsReader = new AppSettingsReader();
        //    string _CultureInfo = _AppSettingsReader.GetValue("CultureInfo", typeof(string)).ToString();
        //    return _CultureInfo;
        //}

        private void WriteSessionLog(UserContext pUserSession)
        {
            const string constSessionLoggerOn = "SessionLoggerOn";
            const string constSessionLogFileName = "SessionLogFileName";
            string _ServerRootPath = Server.MapPath("~/");
            AppSettingsReader _AppSettingsReader = new AppSettingsReader();
            string lIsExceptionLoggerOn = _AppSettingsReader.GetValue(constSessionLoggerOn, typeof(string)).ToString();
            string lFullPathLogFileName = _AppSettingsReader.GetValue(constSessionLogFileName, typeof(string)).ToString();
            if (lIsExceptionLoggerOn == "True")
            {
                if (lFullPathLogFileName != "DataBase")
                {
                    lFullPathLogFileName = _ServerRootPath + _AppSettingsReader.GetValue(constSessionLogFileName, typeof(string)).ToString();
                    string lLogText = string.Empty;
                    lLogText = "UserSessionID - " + pUserSession.UserSessionID + " , UserIPAddress - " + pUserSession.UserIPAddress + " , UserSessionStartTime - " + pUserSession.UserSessionStartTime + " , UserBrowser - " + pUserSession.UserBrowser;
                    FileUtility lFileUtility = new FileUtility();
                    lFileUtility.WriteToLogFile(lLogText, lFullPathLogFileName);
                }
                else
                {
                    Sys_SessionLog lSys_SessionLog = new Sys_SessionLog();
                    SiteAdministrationBus lSiteAdministrationBus = new SiteAdministrationBus();
                    lSys_SessionLog.UserSessionID = pUserSession.UserSessionID;
                    lSys_SessionLog.UserIPAddress = pUserSession.UserIPAddress;
                    lSys_SessionLog.UserBrowserName = pUserSession.UserBrowser;
                    lSys_SessionLog.Sys_CreatedByID = pUserSession.Sys_CreatedByID;

                    lSys_SessionLog.UserSessionStartTime = DateTime.Parse(pUserSession.UserSessionStartTime);

                    if (lSiteAdministrationBus.SaveUserSys_SessionLogDetails(lSys_SessionLog))
                    {

                    }
                }
            }
        }
        #endregion Private Methods

    }
}
